/*
 * 二分查找是在排好序的情况下一种比较简单快速的查找
 */
#include <stdio.h>

#define MAX	5
int binsearch(int a[], int val);

int main()
{
	int a[MAX] = {1, 6, 12, 110, 209};
	int ret;

	ret = binsearch(a, 110); 
	if ( ret < 0)
		printf("Not found\n");
	else
		printf("Found:index = %d\n", ret);

	return 0;
}

int binsearch(int a[], int val)
{
	int l  = 0;
	int r = MAX - 1;
	int m;

	while (l <= r) {
		m = l + (r - l)/2;
		if (a[m] < val)
			l = m + 1;
		else if (a[m] > val)
			r = m - 1;
		else
			return m;
	}

	return -1;
}

